package com.clp.protocol.iec104.iec104.apdu.asdu.infoobj.qua;

import com.clp.protocol.core.nbytepdu.BaseNBytePduClip;
import com.clp.protocol.core.pdu.ByteToStringFormat;
import com.clp.protocol.iec104.iec104.definition.Tm;
import com.clp.protocol.iec104.iec104.definition.TypeTag;
import io.netty.buffer.ByteBuf;
import lombok.Getter;

import java.util.Objects;
import java.util.function.Consumer;

/**
 * 遥测限定词（即品质描述词）
 */
@Getter
public abstract class TmQua extends Qua {
    private Tm.Valid valid;

    protected TmQua(TypeTag typeTag, Tm.Valid valid) {
        super(typeTag);
        this.valid = valid;
    }

    @Override
    public TmQua refreshFrom(ByteBuf buf) {
        byte val = buf.readByte();
        this.valid = Tm.Valid.gain((val & 0x80)==0x80 ? 1 : 0);
        return this;
    }

    @Override
    public boolean isValid() {
        return valid != null;
    }

    @Override
    public void writeBytesTo(ByteBuf buf) {
        buf.writeByte(generateByte());
    }

    private byte generateByte() {
        byte by = 0x00;
        by |= valid.getVal() == 1 ? 0x80 : 0x00;
        return by;
    }

    @Override
    public void writeFormattedByteStringsTo(StringBuilder sb, String frameClipBytesSeparator, String byteSeparator, ByteToStringFormat byteFormat) {
        sb.append(byteFormat.format(generateByte()));
    }

    @Override
    public void writeSimpleDescriptionTo(StringBuilder sb) {
        sb.append(valid.getVal());
    }

    @Override
    public void writeDetailDescriptionTo(StringBuilder sb) {
        sb.append(valid.getDesc()).append("(").append(valid.getVal()).append(")");
    }

    @Override
    protected void forEachOneLevelChild(Consumer<BaseNBytePduClip<?>> consumer) {
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        TmQua tmQua = (TmQua) o;
        return valid == tmQua.valid;
    }

    @Override
    public int hashCode() {
        return Objects.hash(valid);
    }
}
